package org.charry.lib.commons.md5;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.charry.lib.commons.log.StackUtility;


public class MD5 {
	private static Log log = LogFactory.getLog(MD5.class);

	public String getMD5(File file) {
		if (!file.isFile()) {
			return "";
		}

		MessageDigest md = null;
		FileInputStream fis = null;
		byte buffer[] = new byte[1024];
		int len;
		try {
			md = MessageDigest.getInstance("MD5");
			fis = new FileInputStream(file);
			while ((len = fis.read(buffer, 0, 1024)) != -1) {
				md.update(buffer, 0, len);
			}
		} catch (Exception e) {
			StackUtility.logStackTrace(log, e);
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					StackUtility.logStackTrace(log, e);
				} catch (Exception e) {
					StackUtility.logStackTrace(log, e);
				}

				fis = null;
			}
		}

		BigInteger bigInt = new BigInteger(1, md.digest());

		String s = bigInt.toString(16);

		while (s.length() < 32) {
			s = "0" + s;
		}

		return s;
		// return String.format("%1$032x", bigInt);
	}

	public String getMD5String(String s) {
		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			StackUtility.logStackTrace(log, e);
		}

		md.update(s.getBytes(), 0, s.length());
		BigInteger bigInt = new BigInteger(1, md.digest());

		String s5 = bigInt.toString(16);

		while (s5.length() < 32) {
			s5 = "0" + s;
		}

		return s5;

		// return String.format("%1$032x", bigInt);
	}

	public static void main(String s[]) {
		log.info(new MD5().getMD5(new File("/tmp/xxx.x")));
	}
}
